# news/management/commands/printnews.py

from django.core.management.base import BaseCommand
from django.db.models.expressions import result
from lxml.html.defs import link_attrs

from ...models import NewsArticle,Person
from ...utils.chat import analysis

class Command(BaseCommand):
    help = 'Prints all news articles from the database'

    def handle(self, *args, **kwargs):
        articles = NewsArticle.objects.all().order_by('pub_date')
        for article in articles:
            content = article.content
            # print(content)
            date = article.pub_date
            news_link = article.link
            result1 = analysis(content)
            lines = result1.strip().split('\n')

            print(result1)

            if len(lines) < 3:
                print("返回结果少于三行，无法解析完整的人员信息。")
            else:
                i = 0
                while i < len(lines):
                    name = lines[i] if i < len(lines) else ''
                    position = lines[i+1] if i+1 < len(lines) else ''
                    involvement = lines[i+2] if i+2 < len(lines) else ''

                    print("name:"+ name)
                    print("position:" + position)
                    print("involvement:"+ involvement)

                    if name and position and involvement:
                        # 保存到数据库
                        Person.objects.create(
                            pub_date=date,
                            name=name,
                            position=position,
                            involvement=involvement,
                            link = news_link
                        )
                    else:
                        print(f"从第 {i+1} 行开始的数据不完整，已跳过该条目。")
                        break

                    i += 4

                print("人员信息已成功保存到数据库。")


